"use client"

import { useState } from "react"
import { motion } from "framer-motion"
import { useAuth } from '@/contexts/auth-context'
import Link from "next/link"
import { Search, Calendar, MapPin, Users, Clock, Star, Zap, Globe } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

const mockEvents = [
  {
    id: 1,
    title: "2024全球AI开发者大会",
    description: "汇聚全球顶尖AI专家，探讨人工智能最新发展趋势和技术突破",
    organizer: "AI Global Foundation",
    avatar: "/default-avatar.svg",
    date: "2024-03-15",
    endDate: "2024-03-17",
    time: "09:00",
    location: "北京国家会议中心",
    type: "会议",
    category: "AI/ML",
    attendees: 5000,
    price: "免费",
    status: "报名中",
    tags: ["AI", "机器学习", "深度学习", "技术趋势"],
    thumbnail: "/default-thumbnail.svg",
    isOnline: false,
    isFeatured: true,
  },
  {
    id: 2,
    title: "区块链技术创新峰会",
    description: "探讨区块链在金融、供应链、数字身份等领域的创新应用",
    organizer: "Blockchain Innovation Lab",
    avatar: "/default-avatar.svg",
    date: "2024-03-20",
    endDate: "2024-03-21",
    time: "10:00",
    location: "上海世博中心",
    type: "峰会",
    category: "Blockchain",
    attendees: 2000,
    price: "¥299",
    status: "报名中",
    tags: ["区块链", "DeFi", "NFT", "Web3"],
    thumbnail: "/default-thumbnail.svg",
    isOnline: false,
    isFeatured: false,
  },
  {
    id: 3,
    title: "云原生技术实践工作坊",
    description: "深入学习Kubernetes、Docker、微服务等云原生技术实践",
    organizer: "Cloud Native Community",
    avatar: "/placeholder.svg?height=40&width=40",
    date: "2024-03-25",
    endDate: "2024-03-25",
    time: "14:00",
    location: "线上直播",
    type: "工作坊",
    category: "云计算",
    attendees: 1500,
    price: "免费",
    status: "报名中",
    tags: ["Kubernetes", "Docker", "微服务", "DevOps"],
    thumbnail: "/placeholder.svg?height=200&width=300",
    isOnline: true,
    isFeatured: false,
  },
  {
    id: 4,
    title: "数据科学与机器学习训练营",
    description: "为期3天的密集训练，从数据预处理到模型部署的完整流程",
    organizer: "DataScience Academy",
    avatar: "/placeholder.svg?height=40&width=40",
    date: "2024-04-01",
    endDate: "2024-04-03",
    time: "09:00",
    location: "深圳科技园",
    type: "训练营",
    category: "数据科学",
    attendees: 300,
    price: "¥1999",
    status: "报名中",
    tags: ["数据科学", "机器学习", "Python", "实战项目"],
    thumbnail: "/placeholder.svg?height=200&width=300",
    isOnline: false,
    isFeatured: true,
  },
  {
    id: 5,
    title: "开源软件贡献者聚会",
    description: "开源爱好者的线下聚会，分享开源项目经验和最佳实践",
    organizer: "Open Source Community",
    avatar: "/placeholder.svg?height=40&width=40",
    date: "2024-04-05",
    endDate: "2024-04-05",
    time: "19:00",
    location: "杭州西湖文化广场",
    type: "聚会",
    category: "开源",
    attendees: 200,
    price: "免费",
    status: "报名中",
    tags: ["开源", "GitHub", "社区", "技术分享"],
    thumbnail: "/placeholder.svg?height=200&width=300",
    isOnline: false,
    isFeatured: false,
  },
  {
    id: 6,
    title: "移动应用开发技术沙龙",
    description: "探讨Flutter、React Native等跨平台开发技术的最新进展",
    organizer: "Mobile Dev Guild",
    avatar: "/placeholder.svg?height=40&width=40",
    date: "2024-04-10",
    endDate: "2024-04-10",
    time: "14:00",
    location: "广州天河软件园",
    type: "沙龙",
    category: "移动开发",
    attendees: 150,
    price: "¥99",
    status: "即将开始",
    tags: ["Flutter", "React Native", "移动开发", "跨平台"],
    thumbnail: "/placeholder.svg?height=200&width=300",
    isOnline: false,
    isFeatured: false,
  },
]

const eventTypes = ["全部", "会议", "峰会", "工作坊", "训练营", "聚会", "沙龙"]
const categories = ["全部", "AI/ML", "Blockchain", "云计算", "数据科学", "开源", "移动开发", "Web开发"]
const statusOptions = ["全部", "报名中", "即将开始", "进行中", "已结束"]

export default function EventsPage() {
  const { user, isLoading } = useAuth()
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedType, setSelectedType] = useState("全部")
  const [selectedCategory, setSelectedCategory] = useState("全部")
  const [selectedStatus, setSelectedStatus] = useState("全部")
  const [showOnlineOnly, setShowOnlineOnly] = useState(false)

  const filteredEvents = mockEvents.filter((event) => {
    const matchesSearch =
      event.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      event.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      event.tags.some((tag) => tag.toLowerCase().includes(searchQuery.toLowerCase()))
    const matchesType = selectedType === "全部" || event.type === selectedType
    const matchesCategory = selectedCategory === "全部" || event.category === selectedCategory
    const matchesStatus = selectedStatus === "全部" || event.status === selectedStatus
    const matchesOnline = !showOnlineOnly || event.isOnline

    return matchesSearch && matchesType && matchesCategory && matchesStatus && matchesOnline
  })

  const getStatusColor = (status: string) => {
    switch (status) {
      case "报名中":
        return "bg-green-500/20 text-green-400"
      case "即将开始":
        return "bg-blue-500/20 text-blue-400"
      case "进行中":
        return "bg-yellow-500/20 text-yellow-400"
      case "已结束":
        return "bg-gray-500/20 text-gray-400"
      default:
        return "bg-gray-500/20 text-gray-400"
    }
  }

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return date.toLocaleDateString("zh-CN", { month: "long", day: "numeric" })
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="glass border-white/20 p-8 text-center max-w-md mx-auto rounded-lg">
          <h2 className="text-2xl font-bold text-white mb-4">请先登录</h2>
          <p className="text-white/70 mb-6">您需要登录才能访问技术活动</p>
          <Link href="/auth/login">
            <Button className="bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700">
              前往登录
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 头部 */}
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="text-center mb-12">
          <h1 className="text-responsive-4xl font-bold mb-4 text-gradient-animate">技术活动</h1>
          <p className="text-responsive-xl" style={{ color: "white" }}>
            发现精彩技术活动，拓展人脉网络，提升专业技能
          </p>
        </motion.div>

        {/* 搜索和筛选 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="mb-8"
        >
          <div className="flex flex-col md:flex-row gap-4 mb-6">
            <div className="flex-1 relative">
              <Search
                className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5"
                style={{ color: "white" }}
              />
              <Input
                placeholder="搜索活动、主题..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-12 glass-light border-0 placeholder-gray-400"
                style={{ color: "white" }}
              />
            </div>
            <div className="flex items-center gap-2">
              <label className="flex items-center gap-2 text-sm" style={{ color: "white" }}>
                <input
                  type="checkbox"
                  checked={showOnlineOnly}
                  onChange={(e) => setShowOnlineOnly(e.target.checked)}
                  className="rounded"
                />
                仅显示线上活动
              </label>
            </div>
          </div>

          {/* 类型标签 */}
          <div className="flex flex-wrap gap-2 mb-4">
            {eventTypes.map((type) => (
              <motion.div key={type} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                <Badge
                  variant={selectedType === type ? "default" : "outline"}
                  className={`cursor-pointer transition-all duration-300 ${
                    selectedType === type ? "bg-blue-500 text-white" : "border-gray-500 hover:border-blue-400"
                  }`}
                  style={{ color: "white" }}
                  onClick={() => setSelectedType(type)}
                >
                  {type}
                </Badge>
              </motion.div>
            ))}
          </div>

          {/* 分类和状态筛选 */}
          <div className="flex flex-wrap gap-2">
            {categories.map((category) => (
              <Badge
                key={category}
                variant={selectedCategory === category ? "default" : "outline"}
                className={`cursor-pointer transition-all duration-300 ${
                  selectedCategory === category ? "bg-green-500 text-white" : "border-gray-500 hover:border-green-400"
                }`}
                style={{ color: "white" }}
                onClick={() => setSelectedCategory(category)}
              >
                {category}
              </Badge>
            ))}
            {statusOptions.map((status) => (
              <Badge
                key={status}
                variant={selectedStatus === status ? "default" : "outline"}
                className={`cursor-pointer transition-all duration-300 ${
                  selectedStatus === status ? "bg-purple-500 text-white" : "border-gray-500 hover:border-purple-400"
                }`}
                style={{ color: "white" }}
                onClick={() => setSelectedStatus(status)}
              >
                {status}
              </Badge>
            ))}
          </div>
        </motion.div>

        {/* 精选活动 */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ delay: 0.4 }}
          className="mb-12"
        >
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-responsive-2xl font-bold flex items-center gap-2" style={{ color: "white" }}>
              <Star className="w-6 h-6 text-yellow-400" />
              精选活动
            </h2>
          </div>
          <div className="flex gap-6 overflow-x-auto pb-4 scrollbar-hide">
            {filteredEvents
              .filter((event) => event.isFeatured)
              .map((event, index) => (
                <motion.div
                  key={event.id}
                  initial={{ opacity: 0, x: 20 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: 0.6 + index * 0.1 }}
                  className="flex-shrink-0 w-80"
                >
                  <Card className="event-card card-hover h-full">
                    <div className="relative">
                      <img
                        src={event.thumbnail || "/default-thumbnail.svg"}
                        alt={event.title}
                        className="w-full h-48 object-cover rounded-t-lg"
                      />
                      <div className="absolute top-3 left-3">
                        <Badge className={getStatusColor(event.status)}>{event.status}</Badge>
                      </div>
                      <div className="absolute top-3 right-3">
                        <Badge className="bg-yellow-500/20 text-yellow-400">
                          <Star className="w-3 h-3 mr-1" />
                          精选
                        </Badge>
                      </div>
                      {event.isOnline && (
                        <div className="absolute bottom-3 left-3">
                          <Badge className="bg-blue-500/20 text-blue-400">
                            <Globe className="w-3 h-3 mr-1" />
                            线上
                          </Badge>
                        </div>
                      )}
                    </div>

                    <CardContent className="p-4">
                      <h3
                        className="font-semibold text-lg mb-2 line-clamp-2 hover:text-blue-400 transition-colors cursor-pointer"
                        style={{ color: "white" }}
                      >
                        {event.title}
                      </h3>

                      <p className="text-sm mb-3 line-clamp-2" style={{ color: "#d1d5db" }}>
                        {event.description}
                      </p>

                      <div className="flex items-center gap-2 mb-3">
                        <Avatar className="w-6 h-6">
                          <AvatarImage src={event.avatar || "/default-avatar.svg"} />
                          <AvatarFallback className="text-xs">{event.organizer[0]}</AvatarFallback>
                        </Avatar>
                        <span className="text-sm" style={{ color: "#d1d5db" }}>
                          {event.organizer}
                        </span>
                      </div>

                      <div className="space-y-2 text-sm mb-3" style={{ color: "#9ca3af" }}>
                        <div className="flex items-center gap-1">
                          <Calendar className="w-4 h-4" />
                          <span>
                            {formatDate(event.date)} {event.endDate !== event.date && `- ${formatDate(event.endDate)}`}
                          </span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Clock className="w-4 h-4" />
                          <span>{event.time}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <MapPin className="w-4 h-4" />
                          <span className="truncate">{event.location}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <Users className="w-4 h-4" />
                          <span>{event.attendees} 人参与</span>
                        </div>
                      </div>

                      <div className="flex flex-wrap gap-1 mb-4">
                        {event.tags.slice(0, 3).map((tag) => (
                          <Badge key={tag} variant="outline" className="text-xs" style={{ color: "white" }}>
                            {tag}
                          </Badge>
                        ))}
                      </div>

                      <div className="flex items-center justify-between">
                        <div
                          className="text-lg font-bold"
                          style={{ color: event.price === "免费" ? "#4ade80" : "#60a5fa" }}
                        >
                          {event.price}
                        </div>
                        <Button
                          size="sm"
                          className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600"
                          style={{ color: "white" }}
                        >
                          立即报名
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                </motion.div>
              ))}
          </div>
        </motion.div>

        {/* 所有活动 */}
        <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: 0.8 }}>
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-responsive-2xl font-bold flex items-center gap-2" style={{ color: "white" }}>
              <Zap className="w-6 h-6 text-purple-400" />
              所有活动 ({filteredEvents.length})
            </h2>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {filteredEvents.map((event, index) => (
              <motion.div
                key={event.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 1 + index * 0.1 }}
              >
                <Card className="event-card card-hover h-full">
                  <div className="relative">
                    <img
                      src={event.thumbnail || "/default-thumbnail.svg"}
                      alt={event.title}
                      className="w-full h-48 object-cover rounded-t-lg"
                    />
                    <div className="absolute top-3 left-3">
                      <Badge className={getStatusColor(event.status)}>{event.status}</Badge>
                    </div>
                    <div className="absolute top-3 right-3">
                      <Badge variant="outline" className="bg-black/50" style={{ color: "white" }}>
                        {event.type}
                      </Badge>
                    </div>
                    {event.isOnline && (
                      <div className="absolute bottom-3 left-3">
                        <Badge className="bg-blue-500/20 text-blue-400">
                          <Globe className="w-3 h-3 mr-1" />
                          线上
                        </Badge>
                      </div>
                    )}
                  </div>

                  <CardContent className="p-4">
                    <h3
                      className="font-semibold text-lg mb-2 line-clamp-2 hover:text-blue-400 transition-colors cursor-pointer"
                      style={{ color: "white" }}
                    >
                      {event.title}
                    </h3>

                    <p className="text-sm mb-3 line-clamp-2" style={{ color: "#d1d5db" }}>
                      {event.description}
                    </p>

                    <div className="flex items-center gap-2 mb-3">
                      <Avatar className="w-6 h-6">
                        <AvatarImage src={event.avatar || "/default-avatar.svg"} />
                        <AvatarFallback className="text-xs">{event.organizer[0]}</AvatarFallback>
                      </Avatar>
                      <span className="text-sm" style={{ color: "#d1d5db" }}>
                        {event.organizer}
                      </span>
                    </div>

                    <div className="space-y-1 text-xs mb-3" style={{ color: "#9ca3af" }}>
                      <div className="flex items-center gap-1">
                        <Calendar className="w-3 h-3" />
                        <span>{formatDate(event.date)}</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <MapPin className="w-3 h-3" />
                        <span className="truncate">{event.location}</span>
                      </div>
                      <div className="flex items-center gap-1">
                        <Users className="w-3 h-3" />
                        <span>{event.attendees} 人</span>
                      </div>
                    </div>

                    <div className="flex flex-wrap gap-1 mb-4">
                      {event.tags.slice(0, 2).map((tag) => (
                        <Badge key={tag} variant="outline" className="text-xs" style={{ color: "white" }}>
                          {tag}
                        </Badge>
                      ))}
                    </div>

                    <div className="flex items-center justify-between">
                      <div
                        className="text-sm font-bold"
                        style={{ color: event.price === "免费" ? "#4ade80" : "#60a5fa" }}
                      >
                        {event.price}
                      </div>
                      <Button
                        size="sm"
                        className="bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600"
                        style={{ color: "white" }}
                      >
                        报名
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              </motion.div>
            ))}
          </div>
        </motion.div>

        {/* 空状态 */}
        {filteredEvents.length === 0 && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center py-12">
            <div className="text-6xl mb-4">📅</div>
            <h3 className="text-xl font-semibold mb-2" style={{ color: "white" }}>
              没有找到匹配的活动
            </h3>
            <p style={{ color: "#d1d5db" }}>尝试调整筛选条件或搜索关键词</p>
          </motion.div>
        )}
      </div>
    </div>
  )
}
